##PBAR_ExamineFD.py
#
# Make a whole bunch of exploratory plots
#
# 5/1/2013, John Kwong

### PLOTS ###
# Plot all the spectra for a list of datasets
groupNameList  = np.array(('ActiveBackground', 'AirDU', 'WaterDU', 'IronDU'))
# groupNameList  = ['ActiveBackground']

logPlot = 1
filterSpectra = False
normalizeAmplitude = False
normalizeCount = False
subplotx = 4
subploty = 4
subSetIndexList = list(np.arange(8))
subSetIndexList = list(np.arange(5,10))
subSetIndexList = [4]


# cycle through detectors
for detectorNo in np.arange(40):
    # Generate a new figure window if filled.
    if ((detectorNo % (subplotx * subploty)) == 0):
        f, ax = plt.subplots(subploty, subplotx, sharex='col', sharey='row')
    # Calculate subplot window index
    ii = detectorNo/subploty  - 4*(detectorNo / (subplotx * subploty))
    jj = detectorNo%subplotx
    
    # Cycle through the dataset lists
    for nn in np.arange(len(groupNameList)):
        for dd in subSetIndexList:
            index = datasetGroupsIndices[groupNameList[nn]][dd]  # plot only one
            temp = dat[index][detectorNo,:]
            if filterSpectra:
                temp = ndimage.filters.gaussian_filter(temp, 1, order = 0)
            if normalizeAmplitude:
                temp = temp / temp[0:50].max()
            if normalizeCount:
                temp = temp / temp[0:250].sum()                        
            ax[ii][jj].plot(temp, label = prefixList[index])
        ax[ii][jj].set_title(str(detectorNo+1))
        
        if ( ii == 0 and jj == 0):
            legend_ = ax[ii][jj].legend()
            # change font size
        if logPlot:
            ax[ii][jj].set_yscale('log')
        else:
            if (not normalizeAmplitude and  not normalizeCount):
                ax[ii][jj].set_ylim((0,20000))            
            ax[ii][jj].set_xlim((0,50))
 
# plot all spectra for a list of detectors
groupName =  'NoSampleAir'
# groupName =  'NoSampleFe'
# groupName =  'NoSampleH2O'
##groupName = 'NoSampleBackground'
detectorNumber = 35
plt.figure()

index = datasetGroupsIndices[groupName][0]
detectorList = plastic
detectorList = liquid[0:8]

for ii in range(len(detectorList)):
    i = detectorList[ii]
    #plt.plot(dat[index][i,:], label = prefixList[i] + ', ' + str(i+1))
    plt.plot(ndimage.filters.gaussian_filter(dat[index][i,:], 4, order = 0) , label = prefixList[i] + ', ' + str(i+1) + ', filtered')

plt.title('detector' + str(detectorNumber))
plt.legend(loc = 1)
plt.show()
#plt.yscale('log')

# FILTERED WAVEFORM AND SLOPE OF FILTERED WAVEFORM

groupName =  'NoSampleAir'
# groupName =  'NoSampleFe'
# groupName =  'NoSampleH2O'
##groupName = 'NoSampleBackground'
detectorNumber = 35
plt.figure()

index = datasetGroupsIndices[groupName][0]
detectorList = plastic
detectorList = liquid[0:8]

for ii in range(len(detectorList)):
    i = detectorList[ii]
    #plt.plot(dat[index][i,:], label = prefixList[i] + ', ' + str(i+1))
    plt.plot(diff(ndimage.filters.gaussian_filter(dat[index][i,:], 4, order = 0)) , label = prefixList[i] + ', ' + str(i+1) + ', filtered')

plt.title('detector' + str(detectorNumber))
plt.legend(loc = 1)
plt.show()
#plt.yscale('log')

### try fitting a line to the tail ###

# fit parameters
groupName =  'NoSampleAir'
index = datasetGroupsIndices[groupName][0]
detectorList = liquid
detectorNo = detectorList[5]
detectorNo = 0

binFitBound = np.array([60, 100])
index = 2

# Repeatedly fit lines to the spectrum with different bin windows
pfit = np.zeros((10,2))
bins = np.arange(dat[index][detectorNo,:].shape[0])
jj = 0
for ii in range(0,20,2):
    temp = binFitBound + ii
    cut = (bins > temp[0]) & ( bins < temp[1])
    pfit[jj,:] = np.polyfit(bins[cut], log(dat[index][detectorNo,cut]), 1)
    jj = jj + 1
plt.figure()
plot(bins, log(dat[index][detectorNo,:]))
for ii in range(pfit.shape[0]):
    plot(bins, np.polyval(pfit[ii,:], bins))



# EXAMINE SPECTRA ACROSS DATASETS

#groupName =  'NoSampleAir'
#groupName =  'NoSampleFe'
#groupName =  'NoSampleH2O'
groupName = 'NoSampleBackground'
groupName = 'ActiveBackground'
detectorNumber = 29
detectorNumber = 30

plt.figure()
indices = datasetGroupsIndices[groupName]

for ii in range(len(indices)):
    i = indices[ii]
    plt.plot(dat[i][detectorNumber,:], label = prefixList[i])
plt.title('detector' + str(detectorNumber))
plt.show()
plt.yscale('log')

# EXAMINE SPECTRA ACROSS DATASETS, MATCH MAX AMPLITUDE
groupName = 'ActiveBackground'
#detGroups['plastic'] = plastic
#detGroups['liquid'] = liquid
#detGroups['good'] = np.hstack((np.arange(21), 24))
#detGroups['notgood'] = np.array((22, 23, 24, 26, 27, 28, 29, 34, 36, 38)) - 1
#detGroups['bad'] = np.array((30, 31, 32, 33, 35, 39)) - 1
#detGroups['broken'] = 36

detectorNo = detGroups['good'][0]
#detectorNo = detGroups['notgood'][0]
#detectorNo = detGroups['bad'][0]

#detectorNo = 30
filterSpectra = True
normalizeAmplitude = False
normalizeCount = False
plt.figure()

indicesList = datasetGroupsIndices[groupName]

for ii in range(len(indicesList)):
    # dataset index
    i = indicesList[ii]
    # unmodified spectrum
    temp = dat[i][detectorNo,:]
    # modify the spectrum
    if filterSpectra:
        temp = ndimage.filters.gaussian_filter(temp, 1, order = 0)
    if normalizeAmplitude:
        temp = temp / temp[0:50].max()
    if normalizeCount:
        temp = temp / temp[0:250].sum()
    plt.plot(temp, label = (prefixList[i] + ', ' + datasetDescription[i]))
plt.title('detector' + str(detectorNo+1))
plt.show()
#plt.yscale('log')
plt.legend(loc = 1)
